package com.xxl.job.admin.rest;

import java.util.Date;

import javax.inject.Inject;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

import com.ibm.risk.common.rest.RestService;
import com.xxl.job.admin.core.model.JobInfo;
import com.xxl.job.admin.core.model.JobLogGlue;
import com.xxl.job.admin.dao.IJobInfoDao;
import com.xxl.job.admin.dao.IJobLogGlueDao;
import com.xxl.job.core.biz.model.ReturnT;

/**
 * job code controller
 * @author xuxueli 2015-12-19 16:13:16
 */
@RestService
@Path("/jobcode")
public class JobCodeResource {
	
	@Inject
	private IJobInfoDao xxlJobInfoDao;
	@Inject
	private IJobLogGlueDao xxlJobLogGlueDao;

	@Path("/save")
	@POST
	public ReturnT<String> save(JobInfo jobInfo) {
		// valid
		if (jobInfo.getGlueRemark() == null) {
			return new ReturnT<String>(500, "请输入备注");
		}
		if (jobInfo.getGlueRemark().length() < 4 || jobInfo.getGlueRemark().length() > 100) {
			return new ReturnT<String>(500, "备注长度应该在4至100之间");
		}
		JobInfo exists_jobInfo = xxlJobInfoDao.loadById(jobInfo.getId());
		if (exists_jobInfo == null) {
			return new ReturnT<String>(500, "参数异常");
		}
		
		// update new code
		exists_jobInfo.setGlueSource(jobInfo.getGlueSource());
		exists_jobInfo.setGlueRemark(jobInfo.getGlueRemark());
		exists_jobInfo.setGlueUpdatetime(new Date());
		xxlJobInfoDao.update(exists_jobInfo);

		// log old code
		JobLogGlue xxlJobLogGlue = new JobLogGlue();
		xxlJobLogGlue.setJobId(exists_jobInfo.getId());
		xxlJobLogGlue.setGlueType(exists_jobInfo.getGlueType());
		xxlJobLogGlue.setGlueSource(jobInfo.getGlueSource());
		xxlJobLogGlue.setGlueRemark(jobInfo.getGlueRemark());
		xxlJobLogGlueDao.save(xxlJobLogGlue);

		// remove code backup more than 30
		xxlJobLogGlueDao.removeOld(exists_jobInfo.getId(), 30);

		return ReturnT.SUCCESS;
	}
	
}
